﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using Core.DataAccess.IRepositories;

namespace Core.DataAccess.Repositories
{
    [Export(typeof(IFileImgCoverRepository))]
    public class FileImgCoverRepository : IFileImgCoverRepository
    {
        private Connection conn;

        public FileImgCoverRepository()
        {
            conn = new Connection();
        }

        public FileImgCover GetFileImgCoverByAccountID(int accountID)
        {
            using (MXHEntities context = conn.GetContext())
            {
                var item = from fi in context.FileImgCovers
                           where fi.AccountID == accountID
                           orderby fi.FileID descending
                           select fi;
                return item.Count() > 0 ? item.FirstOrDefault() : null;
            }
        }

        public long SaveFileImgCover(FileImgCover fileImgCover)
        {
            using (MXHEntities context = conn.GetContext())
            {
                if (fileImgCover.FileID > 0)
                {
                    context.FileImgCovers.Attach(new FileImgCover { FileID = fileImgCover.FileID });
                    context.FileImgCovers.ApplyCurrentValues(fileImgCover);
                }
                else
                {
                    fileImgCover.CreateDate = DateTime.Now;
                    context.FileImgCovers.AddObject(fileImgCover);
                }
                context.SaveChanges();
            }
            return fileImgCover.FileID;
        }
    }
}
